package com.example.rxjavautildemo.base.base;

import android.os.Looper;
import android.view.View;
import android.widget.TextView;

import com.example.rxjavautildemo.R;
import com.example.rxjavautildemo.base.BaseFragment;
import com.example.rxjavautildemo.entity.EventKey;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.rxutil2.rxbus.SubscribeInfo;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public abstract class BaseRxBusTestFragment extends BaseFragment {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;

    protected SubscribeInfo mSubscribeInfo;

    public void stTitle(String title){
        tvTitle.setText(title);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_rxbus_test;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initListener() {
        mSubscribeInfo = RxBusUtils.get().onMainThread(EventKey.EVENT_CLEAR, String.class, new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                showContent("");
            }
        });
    }

    public void showContent(String eventName,final String msg){
        showContent("事件Key:" + eventName + "\n" + msg);
    }
    public boolean isMainLooper(){
        return Looper.myLooper() == Looper.getMainLooper();
    }

    public void showContent(final String msg){
        if (isMainLooper()) {
            tvContent.setText(msg);
        }else{
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvContent.setText(msg);
                }
            });
        }
    }

    protected abstract void onCancelEvent();

    @Override
    public void onDestroy() {
        onCancelEvent();
        super.onDestroy();
    }

    @OnClick({R.id.bt_cancel,R.id.bt_clear})
    protected void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.bt_cancel:
                onCancelEvent();
                break;
            case R.id.bt_clear:
                showContent("");
                break;
            default:
                break;
        }
    }
}
